using System.Text;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading.Tasks;

public class DbLoader{
   private List<string> files=new List<string>();
   public DbLoader(string Base)
   {
 
     
      SqlConFactory.SetConnection($"server=127.0.0.1;port=3306;user=root;password=yh123; database={Base}");
      DataTable dataTable=new DataTable();
      MysqlHerper.getHerper().GetData("show tables;",dataTable);
      if (!Directory.Exists(Directory.GetCurrentDirectory().Split("/bin")[0]+"/Model"))
      {
         Directory.CreateDirectory(Directory.GetCurrentDirectory().Split("/bin")[0] + "/Model");
      }
      foreach(DataRow row in dataTable.Rows){
         
         String Code=CreataModel(row[0].ToString());
         WriteFile(Code,row[0].ToString());
      }

      
   }

   public async void WriteFile(string Code,string table)
   {
     await Task.Run(new Action(() =>
      {  
         string path = Directory.GetCurrentDirectory().Split("/bin")[0];
         path = path + "/Model/" + table + ".cs";
         if (File.Exists(path))
            return;
         Console.WriteLine("111");
         using (FileStream fs=new FileStream(path,FileMode.Create))
         {
            fs.Write(Encoding.UTF8.GetBytes(Code)); 
         }

      }));
    
   }
   public string CreataModel(string tables){
         string sql=$"desc {tables}";
         DataTable dataTable=new DataTable();
         MysqlHerper.getHerper().GetData($"desc {tables};",dataTable);
         StringBuilder builderModel=new StringBuilder();
         builderModel.Append($"public class {tables}");
         builderModel.Append("\n");
         builderModel.Append("{\n");
         foreach(DataRow row in dataTable.Rows)
         {
            if (!row["Key"].ToString().Trim().Equals(""))builderModel.Append($"    [{row["Key"]}] \r\n");
            if (row["Null"].Equals("NO") ) builderModel.Append("    [NotNullAtter] \r\n");
           
               builderModel.Append($"    public { DbCodeMapper.getMapper(row["Type"].ToString())} ");
               builderModel.Append($"{row["Field"].ToString()}");
               builderModel.Append("{get;set;}");
               builderModel.Append("\n \n");
         }
         builderModel.Append("}");
         return builderModel.ToString();
   }
}